package com.kylin.core.common.web.facade;

import com.kylin.domain.oauth2.social.WechatOauthAuthenticationToken;
import com.kylin.domain.user.vo.WechatUserInfoVO;
import com.kylin.shared.enums.ResultCodeEnum;
import com.kylin.shared.exception.BusinessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * Rest接口控制类基类
 * @author Damon S.
 * @version v1.0.1
 * @date 2021年01月02日 16:32
 */
public abstract class AbstractFacade {

    protected WechatUserInfoVO getWxUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            throw new BusinessException(ResultCodeEnum.AUTH_FAIL);
        }
        WechatOauthAuthenticationToken token;
        if (authentication instanceof WechatOauthAuthenticationToken) {
            token = (WechatOauthAuthenticationToken) authentication;
        } else {
            throw new BusinessException(ResultCodeEnum.AUTH_FAIL);
        }
        if (token.getPrincipal() instanceof WechatUserInfoVO) {
            return (WechatUserInfoVO) token.getPrincipal();
        }
        throw new BusinessException(ResultCodeEnum.USER_NOT_EXIST);
    }
}
